<template>
  <div class="contain">
    <!-- 小导航栏 -->
    <tz-breadcrumb  :pathArr='[{"name": "场景管理"},{"name": "餐厅管理", "url": "/home"},{"name": "新增餐厅", "url": "/add-restaurant"}]'></tz-breadcrumb>
    <!-- 这里是新增餐厅页面 -->
    <div class="add-restaurant">{{id?'修改餐厅':'新增餐厅'}}</div>
    <!-- 基本信息设置 -->
    <div class="introduct-info">
      <div class="init">基本信息设置</div>
      <div class="content">
        <div class="left">
          <!-- 餐厅名称 -->
          <div class="rest-type">
            <div>
              <span class="type-txt">餐厅名称</span>
              <el-input style="width:415px" v-model="restaurant_name" placeholder="请填写餐厅名称"></el-input>
            </div>
            <div v-show="restaurant_name_show" class="warn">*请填写餐厅名称（只允许输入中英文及空格）</div>
          </div>
          <!-- 餐厅楼层 -->
          <div class="rest-type">
            <div >
              <span class="type-txt">餐厅楼层</span> 
              <el-input style="width:415px" v-model="restaurant_floor" placeholder="请填写餐厅楼层"></el-input>
            </div>
            <div v-show="restaurant_floor_show" class="warn">*请填写餐厅楼层（只允许输入数字）</div>
          </div>
          <!-- 餐厅指引 -->
          <div class="rest-type">
            <div >
              <span class="type-txt">餐厅指引</span> 
              <el-input  type="text" style="width:415px" v-model="restaurant_address" placeholder="请填写餐厅指引" maxlength="30" show-word-limit ></el-input>
            </div> 
            <div v-show="restaurant_address_show" class="warn">*请将字数限制在30字之内</div>
          </div>
          <!-- 营业时间 -->
          <div class="business-hours">
            <span class="type-open">营业时间</span>
            <div style="display:inline-block" v-for="item in week" :key="item.index">
              <el-button type="warning" style="margin-left:10px" plain>{{item}}</el-button>
            </div>
          </div>
          <!-- 预定时段 -->
          <!-- <div class="scheduled">
            <div class="scheduled-time">预订时段</div>
            <div class="scheduled-sel-time">
              
              <div v-for="(item,index) in selectTime" :key="item.index" @mouseenter="onMouseOver(index)">
                <el-time-picker  style="width:360px;margin-top:15px" is-range v-model="value4" range-separator="—" start-placeholder="开始时间" end-placeholder="结束时间" placeholder="选择时间范围">
                </el-time-picker>
                <div class="time-delete" v-show="index == i">
                  <img src="./../../public/img/ic_delete.png" alt="">
                  <span @click="deleteNewTime">删除时段</span>
                </div>
              </div>
              <div class="add-new-time" @click="addNewTime">+新增时段</div>
            </div>
          </div> -->
          <!-- 右侧公告 -->
          <div class="rest-type">
            <div>
              <span class="type-txt">公告</span> 
              <el-input style="width:415px" v-model="restaurant_notice" placeholder="请填写餐厅公告（30字之内）" maxlength="30"></el-input>
            </div>
            <div v-show="restaurant_notice_show" class="warn warn-left">*请将字数限制在30字之内</div>
          </div>
          <!-- 右侧简介 -->
          <div class="rest-type">
            <div>
              <span class="introduction type-txt">简介</span> 
              <el-input style="width:415px" v-model="restaurant_introduction" :rows="5" type="textarea"  placeholder="请填写餐厅简介（50～500字）"  maxlength="500"></el-input>
            </div>
            <div v-show="restaurant_introduction_show" class="warn warn-left">*请将字数限制在50～500字之间</div>
          </div>
        </div>
        <div class="right">
           <!-- 添加头像 -->
          <div style="display:flex;">
            <div class="head-title" >餐厅头像</div>
            <div class="head-portrait">
              <div class="head-portrait-addlog" v-if="img7 == ''">+</div>
              <img :src="showImg + img7" class="imgshow" v-if="img7 != ''"/>
              <div class="img-border"  v-if="img7 == ''"></div>
              <input type="file" name=""  class="avatar-uploader" @change="fileChange($event,'img7')" >
            </div>
          </div>
          <div class="upload-tip">推荐上传尺寸300px*180px</div>
          <!-- 餐厅照片 -->
          <div class="upload-img-list">
            <span class="introduct">餐厅照片</span> 
            <!-- 1照片列表循环 -->
            <div v-for="(item,index) in imgList" :key="item.index">
              <div class="rest-type-border" v-show="index == 0? true:index>0 && imgList[index-1].img != ''? true : false" >
                <img :src="showImg + item.img" class="imgshowlist" v-if='item.img != ""' />
                <img src="./../../public/img/ic-delete.png" style="position:absolute;top:-6px;right:-10px;z-index:99;"  v-if='item.img != ""' @click='deleteImg(index)' alt="">
                <div class="img-border-list" v-if="item.img == ''">
                  <div>+</div>
                </div>
                <input type="file" name=""  class="avatar-uploader avatar-uploader-other" @change="fileChangeOther($event,item.img,index)" >
              </div>
            </div>
            <!-- 2照片列表循环 -->
            <!-- <div class="rest-type-border" v-if="img1 != ''">
              <img :src="showImg + img2" class="imgshowlist" v-if='img2 != ""' />
              <div class="img-border-list"  v-if="img2 == ''">
                <div>+</div>
              </div>
              <input type="file" name=""  class="avatar-uploader avatar-uploader-other" @change="fileChangeOther($event,'img2')" >
            </div> -->

            <!-- 3照片列表循环 -->
            <!-- <div class="rest-type-border" v-if="img2 != ''">
              <img :src="showImg + img3" class="imgshowlist" v-if='img3 != ""' />
              <div class="img-border-list"  v-if="img3 == ''">
                <div>+</div>
              </div>
              <input type="file" name=""  class="avatar-uploader avatar-uploader-other" @change="fileChangeOther($event,'img3')" >
            </div> -->

            <!-- 4照片列表循环 -->
            <!-- <div class="rest-type-border" v-if="img3 != ''">
              <img :src="showImg + img4" class="imgshowlist" v-if='img4 != ""' />
              <div class="img-border-list"  v-if="img4 == ''">
                <div>+</div>
              </div>
              <input type="file" name=""  class="avatar-uploader avatar-uploader-other" @change="fileChangeOther($event,'img4')" >
            </div> -->

            <!-- 5照片列表循环 -->
            <!-- <div class="rest-type-border" v-if="img4 != ''">
              <img :src="showImg + img5" class="imgshowlist" v-if='img5 != ""' />
              <div class="img-border-list"  v-if="img5 == ''">
                <div>+</div>
              </div>
              <input type="file" name=""  class="avatar-uploader avatar-uploader-other" @change="fileChangeOther($event,'img5')" >
            </div>-->
          </div> 
          <!-- 推荐尺寸 -->
          <div class="upload-tip">推荐上传尺寸300px*180px</div>
          <!-- 推荐上架 -->
          <div class="recommend-sure">
            <div class="head-recommend">推荐上架</div>
            <div style="margin-left:55px">
              <el-radio v-model="radio" label="1">下架</el-radio>
              <el-radio v-model="radio" label="2">上架</el-radio>
            </div>
          </div>  
        </div>
      </div>
    </div>
    <!-- 高级设置 -->
    <div class="advanced-setting">
      <div class="set">高级设置</div>
      <div>
        <div class="unpay">
          <span class="" >是否开启线上付款</span>
          <div style="display:inline-block;margin-left:50px;">
            <el-radio v-model="unpay" label="0">开启</el-radio>
            <el-radio v-model="unpay" label="1">关闭</el-radio>
          </div>
        </div>
        <div class="arrive">
          <span class="type-txt">最快送达时间</span> 
          <el-input style="width:180px" v-model="arrive_time" placeholder="请填写最快出餐时间"></el-input>
          <span class="min">分钟</span> 
        </div>
        <div style="clear:both"></div>
      </div>
    </div>
    <!-- 确定、取消按钮 -->
    <div class="mark-btn">
      <div class="btn">
        <div class="delete btn-type" v-show="this.id" @click="msgIntoDel">删除</div>
        <div class="determine btn-type" @click="msgIntoSure">确定</div>
        <div class="cancle btn-type" @click="msgIntoCancle">取消</div>
      </div>
    </div> 
  </div> 
</template>
  
<script>
import tzBreadcrumb from './../../components/breadcrumb/breadcrumb.vue'
import api from './../../api/api';
import http from './../../config/index';
export default {
	components: {
  	'tz-breadcrumb': tzBreadcrumb
	},
  data () {
    return {
      // imgList: [1],
      // 图片显示域名
      showImg:'http://foodapi.jimanke.com/',
      // 餐厅icon
      avatarImg:'',
      // 图片列表数组
      avatarImgOther:[],
      imgList:[
        {img:''},
        {img:''},
        {img:''},
        {img:''},
        {img:''},
        ],
      // 餐厅列表1-5张图
      img1:'',
      img2:'',
      img3:'',
      img4:'',
      img5:'',
      // 头像图片
      img7:'',
      // 是否上架，默认下架
      radio:'1',
      unpay:'1',
      // 饭店id
      id:'',
      week: ['周一','周二','周三','周四','周五','周六','周日'],
      selectTime: [1,2,3],
      value4:'222',
      // 餐厅名字
      restaurant_name:'',
      // 餐厅楼层
      restaurant_floor:'',
      // 餐厅地址
      restaurant_address:'',
      // 餐厅公告
      restaurant_notice:'',
      // 餐厅简介
      restaurant_introduction:'',
      // 鼠标悬停显示删除时段
      i: -1,
      // 最快送达时间
      arrive_time: '',
      imageUrl: '',
      // 餐厅名称警告显示
      restaurant_name_show: false,
      // 餐厅楼层警告显示
      restaurant_floor_show: false,
      // 餐厅指引警告显示
      restaurant_address_show: false,
      // 公告警告显示
      restaurant_notice_show: false,
       // 简介警告显示
      restaurant_introduction_show: false,
    }
  },
  methods: {
    // 头像上传
    fileChange (event, img) {
      var fileList = event.target.files;
     // console.log(fileList)  //FileList {0: File(38733), length: 1}
     // console.log(fileList[0]) //File(38733)
      http.upImg(api.uploadImg, {
       file: fileList[0] 
      }, response => {
        console.log('成功响应')
        // console.log(response)
        this[img] = response.data[0].path;
        // 保存头像路径，提交表单的时候用
        this.avatarImg = response.data[0].path;
        // console.log(response.data[0].path)
        // console.log(this);
      }, err => {
        console.log(err);
      });
    },
    // 图片删除功能
    deleteImg (i) {
      // 删除一张
      var oo = this.imgList.splice(i, 1);
      // 补充一张空的
      var imgObj = {img:''}
      this.imgList.push(imgObj);
      // console.log(oo)
      // console.log(this.imgList)
    },
    // 餐厅图片上传
    fileChangeOther (event, img,i) {
      var fileList = event.target.files;
      http.upImg(api.uploadImg, {
       file: fileList[0] 
      }, response => {
        console.log('成功响应')
        this.imgList[i].img = response.data[0].path;
        console.log(this.imgList)
        // 保存图片列表路径，提交表单的时候用
        this.avatarImgOther.push(response.data[0].path);
      }, err => {
        console.log(err);
      });
    },
    login () {
      this.$router.push('login')
    },
		add () {
			this.$router.push('login')
    },
    // 新增餐厅信息提交
    msgIntoSure () {
      var that = this;
      console.log(this.$route.query.id)
      console.log(this.imgList)
      var img = [];
      that.imgList.forEach((item) => {
        if(item.img != '' ){
          img.push(item.img)  
        }
      })
      // console.log(img)
      // 当有餐厅id的时候走修改接口
      if(that.$route.query.id && that.$route.query.id != '' ) {
        // console.log(this.avatarImg)
        that.$confirm('确认修改吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            center: true
        }).then(() => {
          var data = {
            'id': that.id,
            'name': that.restaurant_name,
            'floor': that.restaurant_floor,
            'address': that.restaurant_address,
            'notice': that.restaurant_notice,
            'introduction': that.restaurant_introduction,
            'state': that.radio,
            'ewm_logo': that.img7, //avatarImg,
            'service_time':that.arrive_time,
            'img': img.join(','),
            'pay_status': that.unpay
          }
          http.upFile (api.restaurantEdit, data, 
            success => {
              console.log('支付状态修改成功')
              console.log(data)
              console.log(success)
              if(success.code == 10001) {
                that.$message({
                  type: 'success',
                  message: '修改餐厅成功!'
                });
                // this.$router.push('home');
                that.$router.push({
                  path: '/home',
                  query: {
                    restaurantId :that.$route.query.id
                  }
                });
              }
              
            }, fail => {
              console.log(fail);
          })
        }).catch(() => {
          that.$message({
            type: 'info',
            message: '已取消修改'
          });
        })
      }else{
        // 当无餐厅id的时候走新增接口
        // console.log('新增啦...........')
        if(that.restaurant_name == ''){
            that.$message({
                type: 'warning',
                message: '缺少餐厅名称'
            });
          return false;
        }
        if(that.restaurant_floor == ''){
            that.$message({
                type: 'warning',
                message: '缺少餐厅楼层'
            });
          return false;
        }
        if(that.restaurant_address == ''){
            that.$message({
                type: 'warning',
                message: '缺少餐厅指引'
            });
          return false;
        }
        if(that.restaurant_notice == ''){
            that.$message({
                type: 'warning',
                message: '缺少餐厅公告'
            });
          return false;
        }
        if(that.restaurant_introduction == ''){
            that.$message({
                type: 'warning',
                message: '缺少餐厅简介'
            });
          return false;
        }
        if(that.img7 == ''){
            that.$message({
                type: 'warning',
                message: '缺少餐厅头像'
            });
          return false;
        }
        if(img.join(',') == ''){
            that.$message({
                type: 'warning',
                message: '缺少餐厅照片'
            });
          return false;
        }
        if(that.arrive_time == ''){
            that.$message({
                type: 'warning',
                message: '缺少最快送达时间'
            });
          return false;
        }
        that.$confirm('确认新增吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            center: true
        }).then(() => {
            var data = {
              'seller_id': localStorage.getItem("seller_id"), //api.seller_id,
              'name': that.restaurant_name,
              'floor': that.restaurant_floor,
              'address': that.restaurant_address,
              'notice': that.restaurant_notice,
              'introduction': that.restaurant_introduction,
              'state': that.radio,
              'ewm_logo': that.img7, //this.avatarImg 当修改餐厅的时候logo为空所以编辑失败，新增两者都能用，这里改成img7保险
              'service_time':that.arrive_time,
              'img': img.join(','),
              'pay_status': that.unpay
            }
        http.upFile (api.restaurantAdd, data, 
          success => {
            console.log('提交')
            console.log(success)
            if(success.code == 10001) {
                that.$message({
                  type: 'success',
                  message: '新增餐厅成功!'
                });
                that.$router.push('home');
            }
            if(success.code == 10003) {
                that.$message({
                  type: 'warning',
                  message: success.msg
                });
            }
           
          }, fail => {
            console.log(fail);
          })
        }).catch(() => {
          that.$message({
            type: 'info',
            message: '已取消新增'
          });
        })
      
        }
      
    },
    //鼠标悬浮显示删除时段
    onMouseOver (index) {
      this.i = index;
      // console.log('鼠标悬停'+index)
    },
    // 增加时段
    addNewTime () {
      console.log('增加时间 ')
      this.selectTime.push('a');
    },
    // 删除时段
    deleteNewTime () {
      this.selectTime.shift();
    },
    // 取消按钮跳转到首页
    msgIntoCancle () {
      console.log('跳转到首页')
      this.$router.push('home')
    },
    // 删除餐厅
    msgIntoDel () {
      console.log(this.id)
      this.$confirm('确认删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
      }).then(() => {
        http.post(api.restaurantDel, {
        id: this.id
      }, (res) => {
        console.log(res);

        if(res.code == 20000) {
          this.$message({
            type: 'error',
            message: res.msg
          });
        }

        if(res.code == 10001) {
          this.$message({
            type: 'success',
            message: '删除餐厅成功!'
          });
          this.$router.push('home')
        }

      }, (err) => {
        console.log('网络错误');
      });
      }).catch(() => {
        this.$message({
            type: 'info',
            message: '已取消删除'
          });
      })
      
    
    },
    getData () {
      console.log('data')
      http.get(api.restaurantList, {
          seller_id:localStorage.getItem("seller_id"), // 115,
        }, (res) => {
          console.log('res')
          console.log(res);
        }, (err) => {
          console.log('网络错误');
        });
    },
      
      
  },
  watch: {
    // 监听餐厅名称
    'restaurant_name' : function (newval,oldval) {
      var pattern = /^(?=.*\d)|(?=.*[~!@#$%^&*￥()_+`\-={}:";'<>?,.\/]).{0,}$/g;
      // var pattern=/^[a-zA-Z\u4e00-\u9fa5 ]{1,}$/;
      
      if(pattern.test(newval)){
        this.restaurant_name_show = true;
      }else{
        this.restaurant_name_show = false;
      }
      // /[\d]/g
      this.restaurant_name = newval.replace(pattern,'!')
    },
    // 监听餐厅楼层数字控制
    'restaurant_floor' : function (newval,oldval) {
      if((/[^\d]/g).test(oldval)){
        this.restaurant_floor_show = true;
        // this.restaurant_floor = val.replace(/[^\d]/g,'');
      }else{
        this.restaurant_floor_show = false;
      }
      this.restaurant_floor = newval.replace(/[^\d]/g,'');

    },
    // 监听餐厅指引文字控制
    'restaurant_address' : function (val) {
      if(this.restaurant_address.length >= 30){
        this.restaurant_address_show = true;
      }else{
        this.restaurant_address_show = false;
      }
    },
    // 监听公告文字控制
    'restaurant_notice' : function (val) {
      if(this.restaurant_notice.length >= 30){
        this.restaurant_notice_show = true;
      }else{
        this.restaurant_notice_show = false;
      }
    },
    // 监听简介文字控制
    'restaurant_introduction' : function (val) {
      if(this.restaurant_introduction.length >= 500){
        this.restaurant_introduction_show = true;
      }else{
        this.restaurant_introduction_show = false;
      }
    },
  },
  mounted () {
    var that = this;
     // 保存饭店id
    if(that.$route.query.id && that.$route.query.id != ''){
       that.id = that.$route.query.id;
       http.post(api.restaurantDetails, {
            id: that.$route.query.id,
            seller_id: localStorage.getItem("seller_id"), //api.seller_id,
          }, (res) => {
            console.log(res);
            var res = res.data;
            // 修改餐厅时显示图片列表
            var imgList = res.img.split(',');
            // ["uploads/images/imgs/201905/23/362_1558583283_E0lVOzkQp3.jpg"]
            var imgObjList = [];
             //[{img:"uploads/images/imgs/201905/23/362_1558583283_E0lVOzkQp3.jpg"}, {…}]
            // console.log(imgList)
            imgList.forEach((item,index) => {
              var imgObj = {} 
              imgObj.img = item;
              imgObjList[index]=imgObj;
            })
            if(imgObjList.length < 6){
              for(var i = imgObjList.length;i < 5;i++){
                imgObjList.push({img:''})
              }
            }
            // console.log(imgObjList)
            that.imgList = imgObjList;
            that.restaurant_name = res.name;
            that.restaurant_floor = res.floor;
            that.restaurant_address = res.address;
            that.restaurant_notice = res.notice;
            that.restaurant_introduction = res.introduction;
            that.img7 = res.ewm_logo;
            that.radio = res.state.toString();
            that.unpay = res.pay_status.toString();
            that.arrive_time = res.service_time;
          }, (err) => {
            console.log('网络错误');
          });
    }
  }
}
</script>

<style scoped>
.contain{
  font-size: 16px;
  color:#333;
}
.add-restaurant {
  margin: 20px 0 15px 0;
  height: 50px;
  background-color: #fff;
  line-height: 50px;
  padding-left: 25px;
  box-shadow: 0 2px 6px 0 rgba(0, 0, 0, 0.06);
}
.introduct-info {
  padding: 0 25px;
  box-sizing: border-box;
  background-color:#fff;
}
.init {
  border-bottom:1px solid #EFEFEF;
  padding: 14px 0 16px 0;
  box-sizing: border-box;
  margin-bottom: 5px;
}
.content {
  display: flex;
  /* justify-content: space-between; */
}
.rest-type {
  margin: 15px 0;
}
.rest-type-border {
  position:relative;
  width:200px;
  height:120px;
  border:1px solid #ddd;
  margin-left:55px;
  display:flex;
  justify-content:center;
  align-items:center;
  margin-top:20px;
}
.warn {
  padding-left: 83px;
  color: #FF1818;
  font-size: 14px;
}
.warn-left {
  padding-left: 53px;
}
.classification {
  /* border:1px solid pink; */
}
.type-txt {
  margin-right: 15px;
}
.type-open {
  margin-right: 5px;
}
.business-hours {
  display: inline-block;
}
.scheduled {
  display: flex;
  align-items: center;
}
.scheduled-time {
  margin-right: 15px;
}
.scheduled-sel-time {
  /* border:1px solid black */
}
.add-new-time {
  margin:15px 0 0 0;
  color:#FF7537;
}
.time-delete {
  display: inline-block;
  margin-left:15px;
  color:#FF7537;
}
.introduction {
  /* height:104px; */
  display: inline-block;
  margin-bottom:10px;
}
/* 公告 */
.right {
  position: relative;
  /* border: 1px solid red; */
  margin-left: 225px;
  margin-top:20px;
  padding-right: 5  0px;
  max-width: 750px;
}
.introduct {
  position: absolute;
  top: 144px;
  left: -30px;
}
/* 头像上传 */
.avatar-uploader  {
  opacity:0;
  filter:alpha(opacity=0);
  height: 100px;
  width: 100px;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 9;
}
.avatar-uploader-other {
  height: 120px;
  width: 200px;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.head-title {
  position:absolute;
  left:-30px;
  top:10px; 
}
.recommend-sure {
  position:relative;
  margin-top:20px;
}
.head-recommend {
  position:absolute;
  left:-30px;
}
.head-portrait { 
  position:relative;
  margin-left:55px;
}
.head-portrait-addlog {
  position:absolute;
  top:28px;
  left:38px;
  font-size:32px;
  color: #666;
}
.imgshow {
  width: 100px;
  height: 100px;
}  
.imgshowlist {
  width: 200px;
  height: 120px;
}
.img-border {
  width: 100px;
  height: 100px;
  border: 1px solid #ddd
}
.img-border-list {
  font-size:32px;
  display:flex;
  justify-content:center;
  align-items:center;
  width: 200px;
  height: 120px;
  color: #666;
  border: 1px solid #ddd
}
.upload-img-list {
  display:flex;
  /* border:1px solid blue; */
  /* width:100%; */
  flex-wrap:wrap
}
/* 高级设置 */
.advanced-setting {
  margin-top: 15px;
  padding: 0 25px;
  background-color:#fff;
  box-shadow: 0 2px 6px 0 rgba(0, 0, 0, 0.06);
}
.set {
  padding: 14px 0 16px 0;
  box-sizing: border-box;
  border-bottom: 1px solid #EFEFEF;
  font-size: 30px;
}
.arrive {
  float:left;
  line-height:80px;
  margin-left:70px;
}
.unpay {
  float:left;
  line-height:80px;
}
.min {
  margin-left: 15px;
}
/* 按钮 */
.mark-btn { 
  margin:50px 0 193px 0;
}
.btn {
  width: 700px;
  margin: 0 auto;
}
.mark-btn .delete {
  color: red;
}
.btn-type {
  display: inline-block;
  width: 200px;
  border: 1px solid #FF6F2E;
  border-radius: 5px;
  color: #FF6F2E;
  padding: 12px 83px;
  box-sizing: border-box;
  background-color: #FFF1E5;
  cursor: pointer;
}
.determine {
  margin:0 40px;
}
.upload-tip {
  margin:10px 0 0 55px;
  color:#999;
  font-size:12px;
}
.el-input{
  margin-top:10px;
}
.el-button--warning.is-plain{
  margin-bottom:5px;
}
</style>
